package com.zygh.policeasset.service;

import com.zygh.policeasset.utils.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
/* loaded from: police-asset-2.0-0.0.1-SNAPSHOT.jar:BOOT-INF/classes/com/zygh/policeasset/service/TokenService.class */
public class TokenService {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    public String getTokenByName(String username, String password) {
        UserDetails userDetails = null;
        String token = null;
        try {
            userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
        } catch (AuthenticationException e) {
            return null;
        }

        if (StringUtils.isEmpty(userDetails)) {
            return null;
        }

        if (!this.passwordEncoder.matches(password, userDetails.getPassword())) {
            return null;
        }
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
        token = this.jwtTokenUtil.generateToken(userDetails);
        return token;
    }

    public String getTokenByHeader(HttpServletRequest request) {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader == null || !authHeader.startsWith(this.tokenHead)) {
            return null;
        }
        return authHeader.substring(this.tokenHead.length());
    }
}